var express=require('express');
var session=require('express-session');
var flash = require('connect-flash');
var bodyParser=require('body-parser');
var exHbs=require('express-handlebars').create({
    defaultLayout:'main',
    extname:'.hbs',
    helpers:{
        section: function (name, opts) {
            if(!this._sections)this._sections={};
            this._sections[name]=opts.fn(this);
            return null;
        }
    }
    
});
var path=require('path');
var app=express();
app.set('port',5000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(bodyParser());
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret:'btso',
    key:'btso',
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30}
}));

app.engine('hbs',exHbs.engine);

app.get('/',(req,res)=>{
    var name=app.locals.user?app.locals.user.name:'游客-'+Date.now();
    res.setHeader("Access-Control-Allow-Origin", "*");
    
    res.render('index',{
        title:'Home',
        name:name
    });
});


app.get('/grafana',(req,res)=>{
    res.render('grafana',{
        title:'Grafana'
    });
});

app.get('/login',(req,res)=>{
    res.setHeader("Access-Control-Allow-Origin", "*");
    
    res.render('login',{
        title:'Login'
    });
});

app.post('/login',(req,res)=>{
    var body=req.body;
    console.log('body:',body);
    res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    res.setHeader("Access-Control-Allow-Origin", "*");
    
    if(app.locals.user)return req.flash('error','已经登录'),res.redirect('/notify');

    if(body.name == body.pass){
        app.locals.user={
            name:body.name,
            pass:body.pass
        }
        console.log('Login user:',app.locals.user);
        res.redirect('/');
    }else{
        res.redirect('/login');
    }
});

app.get('/logout',(req,res)=>{
    app.locals.user=null;
    res.redirect('/');
});


app.get('/notify',(req,res)=>{
    res.render('notify',{
        title:'通知',
        msg:req.flash('success').toString() || req.flash('error').toString()
    });
});


app.listen(app.get('port'), ()=>{
  console.log('---------------------------','BTSO port:',app.get('port'),'----',new Date().toLocaleTimeString(),'---------------------------');
});